/**
 * Copyright (c) qzsoft All rights reserved.
 *
 * qzsoft.cn
 *
 * 版权所有，侵权必究！
 */

package com.qzsoft.system.modules.permission.role.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qzsoft.system.modules.permission.role.service.SysRoleDataScopeService;
import com.qzsoft.system.repository.sys.dao.SysDeptDao;
import com.qzsoft.system.repository.sys.dao.SysRoleDataScopeDao;
import com.qzsoft.system.repository.sys.entity.SysDeptEntity;
import com.qzsoft.system.repository.sys.entity.SysRoleDataScopeEntity;
import com.qzsoft.jeemis.common.service.BaseService;
import com.qzsoft.jeemis.repository.sqlmapper.SqlMapper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色数据权限
 *
 * @author
 * @since 1.0.0
 */
@Service
public class SysRoleDataScopeServiceImpl extends BaseService implements SysRoleDataScopeService {
	@Autowired
	SysRoleDataScopeDao sysRoleDataScopeDao;
	@Autowired
	SysDeptDao sysDeptDao;
	private final SqlSession sqlSession;

	/**
	 * 构造方法
	 * @param sqlSession
	 */
	public SysRoleDataScopeServiceImpl(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}


	@Override
	public List<String> getDeptIdList(Long roleId) {
		SqlMapper sqlMapper = new SqlMapper(sqlSession);
		String strSql = "select dept_id from sys_role_data_scope where role_id = #{0}";
		List<String> deptIdList = sqlMapper.selectListArgs(strSql, String.class, roleId);
		return deptIdList;
	}
	
	@Override
	public List<String> getBaseCodeList(List<Long> roleIdList) {
	    // TODO Auto-generated method stub
	    return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Long roleId, List<String> deptIdList) {
		//先删除角色数据权限关系
		deleteByRoleIds(new Long[]{roleId});

		//角色没有一个数据权限的情况
		if (CollUtil.isEmpty(deptIdList)) {
			return;
		}
		// 单位数据量少在500以下的可以用这种方式存储 数据量大时使用sql存储
		QueryWrapper<SysDeptEntity> queryWrapper=new QueryWrapper<>();
		queryWrapper.in("id",deptIdList).select("pkid","id");
		List<SysDeptEntity> deptEntities=sysDeptDao.selectList(queryWrapper);

		//保存角色数据权限关系
		for (SysDeptEntity deptEntity  : deptEntities) {
			SysRoleDataScopeEntity sysRoleDataScopeEntity = new SysRoleDataScopeEntity();
			sysRoleDataScopeEntity.setDeptId(deptEntity.getId());
			sysRoleDataScopeEntity.setDeptPkid(deptEntity.getPkid());
			sysRoleDataScopeEntity.setRoleId(roleId);
			//保存
			sysRoleDataScopeDao.insert(sysRoleDataScopeEntity);
		}
	}

	@Override
	public void deleteByRoleIds(Long[] roleIds) {
		QueryWrapper<SysRoleDataScopeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("role_id", roleIds);
		sysRoleDataScopeDao.delete(queryWrapper);

	}
}